package com.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usercenter.entity.UserProfileExtendEntity;
import com.usercenter.mapper.UserProfileMapper;
import com.usercenter.service.UserProfileService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 用户个人资料服务实现
 */
@Service
public class UserProfileServiceImpl extends ServiceImpl<UserProfileMapper, UserProfileExtendEntity> implements UserProfileService {

    @Override
    public UserProfileExtendEntity getProfileByOpenId(String openid) {
        LambdaQueryWrapper<UserProfileExtendEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserProfileExtendEntity::getOpenid, openid);
        return this.getOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProfile(UserProfileExtendEntity profile) {
        profile.setUpdateTime(new Date());
        return this.updateById(profile);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean initProfile(String openid) {
        // 检查是否已存在
        if (getProfileByOpenId(openid) != null) {
            return true;
        }
        
        // 创建新的个人资料
        UserProfileExtendEntity profile = new UserProfileExtendEntity();
        profile.setOpenid(openid);
        profile.setGender(0);  // 默认未知
        profile.setSignature("这个人很懒，什么都没有留下");
        profile.setUpdateTime(new Date());
        
        return this.save(profile);
    }
} 